import GameRule from '../enum/game';
// eslint-disable-next-line no-duplicate-imports
import React from 'react';

const gameInitialState = {
    currentPlayer: 0,
    ending: false,
    endingTar: null,
    executeStep: 0,
    actionChecked: Array(GameRule.MESH_COUNT).fill(null),
};
/**
 * @function reducer reducer方法
 * @param state state
 * @param action 传入参数
 * @returns dispatch内容
 */
function gameReducer (state: any, action: any) {
    const { payload = {} } = action;
    switch (action.type) {
        case 'changePlayer':
            return { ...state, currentPlayer: state.currentPlayer ? 0 : 1 };
        case 'switchAction':
            return { ...state, currentPlayer: payload.clickIndex % 2  === 0 ? 0 : 1 };
        case 'changeEndingState':
            return { ...state, ...payload };
        case 'setActionChecked':
            return { ...state, ...payload };
        case 'changeExecute':
            return { ...state, executeStep: payload.executeStep };
        default:
            throw new Error();
    }
}

interface GameContextType {
    gameState: {
        currentPlayer: number;
        ending: boolean;
        endingTar: null | 'X' | 'O';
        executeStep: number;
        actionChecked: CheckedListData;
    };
    changeState: (action: {type: string, payload?: any}) => void;
}
const GameContext = React.createContext({} as GameContextType);

export {
    gameInitialState,
    gameReducer,
    GameContext
};
